﻿using Autofac;
using Common;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using DBContext;
using EV.EventBus;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using ZoneLine.Common;
using ZoneLine.Models;
using ZoneLine.Models.PrintModeConfig;
using ZoneLine.Models.StationConfig;
using ZoneLine.Printers;
using ZoneLine.Stations;
using ZoneLine.Stations.QOPStation;

namespace ZoneLine.ViewModels
{
    public class MainViewModel : ObservableObject
    {
        private IModelDAL _dal;

        public MainViewModel(IModelDAL dal, QOP006Station qOP006Station, QOP010Station qOP010Station, QOP020Station qOP020Station, QOP050LStation qOP050LStation, QOP050RStation qOP050RStation, QOP060Station qOP060Station)
        {
            _dal = dal;

            InitStationInfo();

            var station006Config = _dal.GetModel<QOP006StationConfig>(p => true);
            Q006Station = qOP006Station;
            Q006Station.Init(station006Config.Ip, 102, station006Config.ReadStartAddr, station006Config.EndUploadCodeAddr, station006Config.EndUploadDataAddr, station006Config.AllowWorkAddr);

            var station010Config = _dal.GetModel<QOP010StationConfig>(p => true);
            Q010Station = qOP010Station;
            Q010Station.Init(station010Config.Ip, 102, station010Config.ReadStartAddr, station010Config.EndUploadCodeAddr, station010Config.EndUploadDataAddr, station010Config.AllowWorkAddr);

            var station020Config = _dal.GetModel<QOP020StationConfig>(p => true);
            Q020Station = qOP020Station;
            Q020Station.Init(station020Config);

            var station050LConfig = _dal.GetModel<QOP050LStationConfig>(p => true);
            Q050LStation = qOP050LStation;
            Q050LStation.Init(station050LConfig.Ip, 102, station050LConfig.ReadStartAddr, station050LConfig.EndUploadCodeAddr, station050LConfig.EndUploadDataAddr, station050LConfig.AllowWorkAddr, station050LConfig.PrinterName);

            var station050RConfig = _dal.GetModel<QOP050RStationConfig>(p => true);
            Q050RStation = qOP050RStation;
            Q050RStation.Init(station050RConfig.Ip, 102, station050RConfig.ReadStartAddr, station050RConfig.EndUploadCodeAddr, station050RConfig.EndUploadDataAddr, station050RConfig.AllowWorkAddr, station050RConfig.PrinterName);
            if (Cache.WorkStationValidationList.Any(A => A.Contains("QOP020Station")))
            {
                QOP060Station = qOP060Station;
                //QOP060Station.Init("192.168.6.128", 102, "DB1000.0", "DB1000.80.4", "DB1000.80.5", "DB1000.80.2");
                QOP060Station.Init("192.168.10.120", 102, "DB1000.0", "DB1000.80.4", "DB1000.80.5", "DB1000.80.2");
            }
            try
            {
                SysCfg.ReloadPrintConfig();
            }
            catch (Exception ex)
            {
                //todo 加载打印配置失败
            }

            Task.Run(() =>
            {
                Q006Station.Start();
            });

            Task.Run(() =>
            {
                Q010Station.Start();
            });

            Task.Run(() =>
            {
                Q020Station.Start();
            });

            Task.Run(() =>
            {
                Q050LStation.Start();
            });

            Task.Run(() =>
            {
                Q050RStation.Start();
            });
            if (Cache.WorkStationValidationList.Any(A => A.Contains("QOP020Station")))
            {
                Task.Run(() =>
                {
                    QOP060Station.Start();
                });
            }
        }

        private void InitStationInfo()
        {
            var config = StationEnableConfig.GetPara();
            if (config.OP006StationEnable == 1)
            {
                Cache.WorkStationValidationList.Add(nameof(QOP006Station));
            }
            if (config.OP020StationEnable == 1)
            {
                Cache.WorkStationValidationList.Add(nameof(QOP020Station));
            }
            if (config.OP010StationEnable == 1)
            {
                Cache.WorkStationValidationList.Add(nameof(QOP010Station));
            }

            if (config.OP050LStationEnable == 1)
            {
                Cache.WorkStationValidationList.Add(nameof(QOP050LStation));
            }
            if (config.OP050RStationEnable == 1)
            {
                Cache.WorkStationValidationList.Add(nameof(QOP050RStation));
            }
        }

        private QOP006Station _q006Station;

        public QOP006Station Q006Station
        {
            get { return _q006Station; }
            set => SetProperty(ref _q006Station, value);
        }

        private QOP060Station _oP060Station;

        public QOP060Station QOP060Station
        {
            get { return _oP060Station; }
            set => SetProperty(ref _oP060Station, value);
        }

        private QOP010Station _q010Station;

        public QOP010Station Q010Station
        {
            get { return _q010Station; }
            set => SetProperty(ref _q010Station, value);
        }

        private QOP020Station _q020Station;

        public QOP020Station Q020Station
        {
            get { return _q020Station; }
            set => SetProperty(ref _q020Station, value);
        }

        private QOP050LStation _q050LStation;

        public QOP050LStation Q050LStation
        {
            get { return _q050LStation; }
            set => SetProperty(ref _q050LStation, value);
        }

        private QOP050RStation _q050RStation;

        public QOP050RStation Q050RStation
        {
            get { return _q050RStation; }
            set => SetProperty(ref _q050RStation, value);
        }

        #region 打印配置

        private bool _enterAuth;

        public bool EnterAuth
        {
            get { return _enterAuth; }
            set => SetProperty(ref _enterAuth, value);
        }

        public RelayCommand SaveConfigCmd => new RelayCommand(() =>
        {
            SysCfg.SavePrintConfig();
        });

        //private RelayCommand _savePrintConfigCmd;

        //public RelayCommand SaveConfigCmd
        //{
        //    get { return _savePrintConfigCmd ?? (_savePrintConfigCmd = new RelayCommand(SavePrintConfig)); }
        //}

        //private void SavePrintConfig()
        //{
        //    var config = ContainerServer.Container.Resolve<PrintConfigTotal>();
        //    try
        //    {
        //        if (!string.IsNullOrEmpty(config.LxqcConfig.ProductType))
        //            _dal.UpdateModelSuper(p => true, config.LxqcConfig);
        //    }
        //    catch (Exception ex)
        //    {

        //        MessageBox.Show("理想汽车打印配置保存失败" + ex.Message);
        //    }

        //    try
        //    {
        //        if (!string.IsNullOrEmpty(config.Sqqc_Config.ProductType))
        //            _dal.UpdateModelSuper(p => true, config.Sqqc_Config);
        //    }
        //    catch (Exception ex)
        //    {
        //        MessageBox.Show("上汽汽车打印配置保存失败" + ex.Message);
        //    }

        //    try
        //    {
        //        if (!string.IsNullOrEmpty(config.BqqcLHConfig.ProductType))
        //            _dal.UpdateModelSuper(p => true, config.BqqcLHConfig);
        //    }
        //    catch (Exception ex)
        //    {
        //        MessageBox.Show("北汽汽车螺簧打印配置保存失败" + ex.Message);
        //    }

        //    try
        //    {
        //        if (!string.IsNullOrEmpty(config.BqqcKhConfig.ProductType))
        //            _dal.UpdateModelSuper(p => true, config.BqqcKhConfig);
        //    }
        //    catch (Exception ex)
        //    {
        //        MessageBox.Show("北汽汽车空簧打印配置保存失败" + ex.Message);
        //    }

        //    try
        //    {
        //        if (!string.IsNullOrEmpty(config.WlqcConfig.ProductType))
        //            _dal.UpdateModelSuper(p => true, config.WlqcConfig);
        //    }
        //    catch (Exception ex)
        //    {
        //        MessageBox.Show("蔚来汽车打印配置保存失败" + ex.Message);
        //    }

        //    try
        //    {
        //        if (!string.IsNullOrEmpty(config.PackageConfigModel.ProductType))
        //            _dal.UpdateModelSuper(p => true, config.PackageConfigModel);
        //    }
        //    catch (Exception ex)
        //    {
        //        MessageBox.Show("打包打印配置保存失败" + ex.Message);
        //    }
        //}

        public RelayCommand ReloadConfigCmd => new RelayCommand(() =>
        {
            SysCfg.ReloadPrintConfig();
        });

        //private RelayCommand _reloadPrintConfigCmd;

        //public RelayCommand ReloadConfigCmd
        //{
        //    get { return _reloadPrintConfigCmd ?? (_reloadPrintConfigCmd = new RelayCommand(ReloadPrintConfig)); }
        //}

        //private void ReloadPrintConfig()
        //{
        //    try
        //    {
        //        var config = ContainerServer.Container.Resolve<PrintConfigTotal>();

        //        var lxqcConfig = _dal.GetModel<LXQC_Config>(p => p.ProductType.Equals(Cache.CurrentProductType));
        //        if (lxqcConfig == null)
        //        {
        //            //_dal.AddModel(new LXQC_Config());
        //            lxqcConfig = new LXQC_Config();
        //        }
        //        config.LxqcConfig = lxqcConfig;

        //        var sqqcConfig = _dal.GetModel<SQQC_Config>(p => p.ProductType.Equals(Cache.CurrentProductType));
        //        if (sqqcConfig == null)
        //        {
        //            //_dal.AddModel(new SQQC_Config());
        //            sqqcConfig = new SQQC_Config();
        //        }
        //        config.Sqqc_Config = sqqcConfig;

        //        var bqqcLHConfig = _dal.GetModel<BQQC_LH_Config>(p => p.ProductType.Equals(Cache.CurrentProductType));
        //        if (bqqcLHConfig == null)
        //        {
        //            //_dal.AddModel(new BQQC_LH_Config());
        //            bqqcLHConfig = new BQQC_LH_Config();
        //        }
        //        config.BqqcLHConfig = bqqcLHConfig;

        //        var bqqcKHConfig = _dal.GetModel<BQQC_KH_Config>(p => p.ProductType.Equals(Cache.CurrentProductType));
        //        if (bqqcKHConfig == null)
        //        {
        //            //_dal.AddModel(new BQQC_KH_Config());
        //            bqqcKHConfig = new BQQC_KH_Config();
        //        }
        //        config.BqqcKhConfig = bqqcKHConfig;

        //        var wlConfig = _dal.GetModel<WLQCConfig>(p => p.ProductType.Equals(Cache.CurrentProductType));
        //        if (wlConfig == null)
        //        {
        //            //_dal.AddModel(new WLQCConfig());
        //            wlConfig = new WLQCConfig();
        //        }
        //        config.WlqcConfig = wlConfig;
        //    }
        //    catch (Exception ex)
        //    {

        //    }
        //}

        private RelayCommand<string> _selectTemplateCmd;

        public RelayCommand<string> SelectTemplateCmd
        {
            get { return _selectTemplateCmd ?? (_selectTemplateCmd = new RelayCommand<string>(SelectTemplate)); }
        }

        private void SelectTemplate(string info)
        {
            FileDialog dia = new OpenFileDialog();
            var rlt = dia.ShowDialog();
            string path = string.Empty;
            if (rlt.HasValue && rlt.Value)
            {
                path = dia.FileName;
            }
            else
            {
                return;
            }
            var config = ContainerServer.Container.Resolve<PrintConfigTotal>();
            switch (info)
            {
                case "LX":
                    config.LxqcConfig.TemplatePath = path;
                    break;

                case "SQ":
                    config.Sqqc_Config.TemplatePath = path;
                    break;

                case "BQLH":
                    config.BqqcLHConfig.TemplatePath = path;
                    break;

                case "BQKH":
                    config.BqqcKhConfig.TemplatePath = path;
                    break;

                case "WL":
                    config.WlqcConfig.TemplatePath = path;
                    break;

                default:
                    break;
            }
        }

        private int _startPrintIndex = 1;

        public int StartPrintIndex
        {
            get { return _startPrintIndex; }
            set => SetProperty(ref _startPrintIndex, value);
        }

        private int _endPrintIndex = 5;

        public int EndPrintIndex
        {
            get { return _endPrintIndex; }
            set => SetProperty(ref _endPrintIndex, value);
        }

        private RelayCommand<string> _printTestCmd;

        public RelayCommand<string> PrintTestCmd
        {
            get { return _printTestCmd ?? (_printTestCmd = new RelayCommand<string>(PrintTest)); }
        }

        private void PrintTest(string s)
        {
            try
            {
                var config = _dal.GetModel<QOP050LStationConfig>(p => true);
                var printConfig = ContainerServer.Container.Resolve<PrintConfigTotal>();
                switch (s)
                {
                    case "LX":
                        var printerLx = new LXQCPrinter();
                        printerLx.PrintLabel(printConfig.LxqcConfig.TemplatePath, config.PrinterName, StartPrintIndex);
                        break;

                    case "SQ":
                        var printerSq = new SQQCPrinter();
                        printerSq.PrintLabel(printConfig.Sqqc_Config.TemplatePath, config.PrinterName, StartPrintIndex, EndPrintIndex);
                        break;

                    case "BQLH":
                        var printerBqLh = new BQLHPrinter();
                        printerBqLh.PrintLabel(printConfig.BqqcLHConfig.TemplatePath, config.PrinterName, StartPrintIndex);
                        break;

                    case "BQKH":
                        var printerBqKh = new BQKHPrinter();
                        printerBqKh.PrintLabel(printConfig.BqqcKhConfig.TemplatePath, config.PrinterName, StartPrintIndex);
                        break;

                    case "WL":
                        var printerWl = new WLQCPrinter();
                        printerWl.PrintLabel(printConfig.WlqcConfig.TemplatePath, config.PrinterName, StartPrintIndex);
                        break;

                    case "LX_Show":
                        Task.Run(() =>
                        {
                            var printerLx_show = new LXQCPrinter();
                            printerLx_show.PrintLabelShow(printConfig.LxqcConfig.TemplatePath, config.PrinterName, StartPrintIndex);
                        });
                        break;

                    case "SQ_Show":
                        Task.Run(() =>
                        {
                            var printerSq_show = new SQQCPrinter();
                            printerSq_show.PrintLabelShow(printConfig.Sqqc_Config.TemplatePath, config.PrinterName, StartPrintIndex);
                        });
                        break;

                    case "BQLH_Show":
                        Task.Run(() =>
                        {
                            var printerBqLh_show = new BQLHPrinter();
                            printerBqLh_show.PrintLabelShow(printConfig.BqqcLHConfig.TemplatePath, config.PrinterName, StartPrintIndex);
                        });
                        break;

                    case "BQKH_Show":
                        var printerBqKh_show = new BQKHPrinter();
                        printerBqKh_show.PrintLabelShow(printConfig.BqqcKhConfig.TemplatePath, config.PrinterName, StartPrintIndex);
                        break;

                    case "WL_Show":
                        var printerWl_show = new WLQCPrinter();
                        printerWl_show.PrintLabelShow(printConfig.WlqcConfig.TemplatePath, config.PrinterName, StartPrintIndex);
                        break;

                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        #endregion 打印配置

        #region 装箱

        //private PackageBoxViewModel _packageBoxView;

        //public PackageBoxViewModel PackageBoxView
        //{
        //    get { return _packageBoxView; }
        //    set => SetProperty(ref _packageBoxView, value);
        //}

        #endregion 装箱

        #region 重打50工位标签

        private RelayCommand<string> _rePrintCmd;

        public RelayCommand<string> RePrintCmd
        {
            get { return _rePrintCmd ?? (_rePrintCmd = new RelayCommand<string>(RePrint)); }
        }

        private void RePrint(string obj)
        {
            MessageCenter.PublishAsync(obj);
        }

        #endregion 重打50工位标签

        #region 模拟弹簧力测试

        private string _testAbsCode;

        /// <summary>
        /// 测试用减震码
        /// </summary>
        public string TestAbsCode
        {
            get { return _testAbsCode; }
            set => SetProperty(ref _testAbsCode, value);
        }

        private string _testSpringCode;

        public string TestSpringCode
        {
            get { return _testSpringCode; }
            set => SetProperty(ref _testSpringCode, value);
        }

        private float _heigthValue;

        /// <summary>
        /// 高度值偏差 从mes获取到的
        /// </summary>
        public float HeigthValue
        {
            get { return _heigthValue; }
            set => SetProperty(ref _heigthValue, value);
        }

        private float _calResult;

        /// <summary>
        /// 计算结果
        /// </summary>
        public float CalResult
        {
            get { return _calResult; }
            set => SetProperty(ref _calResult, value);
        }

        private short _channelResult;

        /// <summary>
        /// 计算出要使用的通道值，展示、写给plc
        /// </summary>
        public short ChannelResult
        {
            get { return _channelResult; }
            set => SetProperty(ref _channelResult, value);
        }

        private RelayCommand _testCalChannelCmd;

        public RelayCommand TestCalChannelCmd
        {
            get { return _testCalChannelCmd ?? (_testCalChannelCmd = new RelayCommand(CalChannel)); }
        }


        private StationDataResult _stationDataResult;

        public StationDataResult StationDataResult
        {
            get { return _stationDataResult; }
            set { _stationDataResult = value; }
        }


        private async void CalChannel()
        {
            var station20 = Q020Station;
            try
            {
                (HeigthValue, CalResult, ChannelResult, StationDataResult) = await station20.CalChannel(TestAbsCode, TestSpringCode);
            }
            catch (Exception ex)
            {
                await MessageCenter.PublishAsync("QOP020Stationuilog", "计算失败，失败原因是" + ex.Message);
            }
        }

        #endregion 模拟弹簧力测试
    }
}